import { getQiniuToken, uploadFile } from "../EditorJs/api"
import { make } from "@/components/EditorJs/utils/dom"
export const uploadFileFn = (cb: (data: any) => void) => {
	const fileDom = make("input", "", { type: "file" })
	fileDom.style.display = "none"
	document.body.append(fileDom)
	fileDom.click()
	fileDom.addEventListener("change", async (event: any) => {
		// 处理文件选择事件
		const file = event.target.files[0]

		const result = await uploadFn(file, () => document.body.removeChild(fileDom))

		cb && cb(result)
	})
}
export const uploadFn = async (file: File, cb?: (args: any) => void) => {
	const result: any = await getQiniuToken()
	if (!result || !result.token) {
		return
	}
	const data = new FormData()
	data.set("file", file)
	data.set("token", result.token)
	const res: any = await uploadFile(data)
	const obj = {
		url: `${result.domain}/${res.key}`,
		name: file.name,
		size: file.size,
		type: file.type,
	}
	cb && cb(obj)
	return obj
}